package org.flow.basic.threadpool;

import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.ThreadFactory;

/**
 * @author xl-9527
 * @since 2024/6/23
 **/
public class CustomThreadFactory implements ThreadFactory {

    private final ThreadGroup threadGroup;

    public CustomThreadFactory() {
        this.threadGroup = System.getSecurityManager() != null ? System.getSecurityManager().getThreadGroup() : Thread.currentThread().getThreadGroup();
    }

    @Override
    public Thread newThread(final Runnable r) {
        return this.getThread(r);
    }

    protected Thread getThread(final Runnable r) {
        // 判读是否饱含 netty 框架，如果饱含使用 FastThreadLocalThread 优化 ThreadLocal 的使用。如果不饱含则直接使用 java.lang.Thread
        try {
            final Class<?> aClass = Class.forName("FastThreadLocalThread");
            return (Thread) aClass.getDeclaredConstructors()[0].newInstance();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            final Thread newThread = new Thread(threadGroup, r, "custom-thread-" + System.currentTimeMillis());
            if (newThread.isDaemon()) {
                newThread.setDaemon(false);
            }
            return newThread;
        }
    }
}
